package net.xujialiang.XTestRPA.Config.SpringSecurityConfig;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.google.gson.Gson;
import com.google.gson.internal.LinkedTreeMap;
import net.xujialiang.XTestRPA.Enum.LogEnum;
import net.xujialiang.XTestRPA.Service.XRPALogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

import java.security.MessageDigest;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Component
public class AdminAuthenticationProvider implements AuthenticationProvider {

    @Autowired
    UserDetailsServiceImpl userDetailsService;

    @Autowired
    XRPALogService logService;

    @Value("${xrpa.tokenSecret}")
    private String tokenSecret;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        // 获取前端表单中输入后返回的用户名、密码
        String userName = (String) authentication.getPrincipal();
        String password = (String) authentication.getCredentials();
        MultiReadHttpServletRequest wrappedRequest = (MultiReadHttpServletRequest) authentication.getDetails();
        Gson gson = new Gson();
        LinkedTreeMap<String,String> user = (LinkedTreeMap<String,String>)gson.fromJson(wrappedRequest.getBodyJsonStrByJson(wrappedRequest), Object.class);

        SecurityUser userInfo = (SecurityUser) userDetailsService.loadUserByUsername(userName, user.get("ttc"));
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        boolean isValid = passwordEncoder.matches(password, userInfo.getPassword());

        // 验证密码
        if (!isValid) {
            String errInfo = "用户名或密码错误!";
            try {
                logService.addLog(LogEnum.Login.getModule(), errInfo, userName, user.get("ttc"));
            } catch (Exception exp) {
                exp.printStackTrace();
            }
            throw new BadCredentialsException(errInfo);
        }

        try{
            // 设置过期时间 默认一年
            Date date = new Date(System.currentTimeMillis() + 31536000*10);
            // 私钥和加密算法
            Algorithm algorithm = Algorithm.HMAC256(tokenSecret);
            // 设置头部信息
            Map<String, Object> header = new HashMap<>(2);
            header.put("Type", "Jwt");
            header.put("alg", "HS256");
            String claimStr = userName + "&&" + password + "&&" + userInfo.getTTC();
            String jwtToken = JWT.create()
                    .withHeader(header)
                    .withClaim("data", claimStr)
                    .withExpiresAt(date)
                    .sign(algorithm);
            userInfo.getCurrentUserInfo().setToken(jwtToken);
            return new UsernamePasswordAuthenticationToken(userInfo, password, userInfo.getAuthorities());
        }catch (Exception e){
            String errInfo = "用户名或密码错误!";
            try {
                logService.addLog(LogEnum.Login.getModule(), errInfo, userName, user.get("ttc"));
            } catch (Exception exp) {
                exp.printStackTrace();
            }
            throw new BadCredentialsException(errInfo);
        }

    }

    @Override
    public boolean supports(Class<?> aClass) {
        return true;
    }
}